<?php

namespace App\Services;

use Illuminate\Http\Request;

class AuditService
{
    /**
     * @param $content
     * @return mixed
     * 内容审核
     */
    public function contentAudit($content)
    {
        $token = $this->getAccessToken('WCWzjiCZVhdCa2gUtpWs5Muj', '553CX0c1TsAAc3rGaU5BSycPpgNbSSdm');

        $url = 'https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token=' . $token;
        $bodys = array(
            'text' => $content
        );
        $res = Curl::postRequest($url, $bodys);

        //结果转成数组
        $res = json_decode($res, true);
        //根据自己的业务逻辑进行处理
        return $res;
    }

    /**
     * @return false|string
     * 图片审核
     */
    public function imageAudit()
    {

        $token = $this->getAccessToken('API Key', 'Secret Key');
        $url = 'https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined?access_token=' . $token;
        $img = file_get_contents('C:\Users\Pictures\Saved Pictures\1.png');
        $img = base64_encode($img);
        $bodys = array(
            'image' => $img
        );
        $res = $this->curlPost($url, $bodys);
        //结果转成数组
        $res = json_encode($res, true);
        //根据自己的业务逻辑进行处理
        return $res;
    }

    /**
     * 获取百度开放平台的票据
     * 参考链接：https://ai.baidu.com/ai-doc/REFERENCE/Ck3dwjhhu
     */
    public function getAccessToken($ApiKey = '', $SecretKey = '', $grantType = 'client_credentials')
    {

        $url = 'https://aip.baidubce.com/oauth/2.0/token';
        $post_data['grant_type'] = $grantType;
        $post_data['client_id'] = $ApiKey;
        $post_data['client_secret'] = $SecretKey;
        $o = "";
        foreach ($post_data as $k => $v) {
            $o .= "$k=" . urlencode($v) . "&";
        }
        $post_data = substr($o, 0, -1);

        $res = Curl::postRequest($url, $post_data);
        //进行把返回结果转成数组
        $res = json_decode($res, true);
        if (isset($res['error'])) {
            exit('API Key或者Secret Key不正确');
        }
        $accessToken = $res['access_token'];
        return $accessToken;
    }
}
